# @Time    : 2025-10-11 15:48
# @Author: Fioman
# @Phone  : 13149920693
# @Tips      : Talk is cheap,show me the code ^_^
import sys
import ctypes
import platform
from datetime import datetime
import subprocess

from eap_control.data_model import DataResult


def set_system_time(target_time_str) -> DataResult:
    """设置系统时间（需要管理员权限）"""
    result = DataResult()
    try:
        # 解析目标时间
        target_time = datetime.strptime(target_time_str, "%Y-%m-%d %H:%M:%S")
        print(f"目标时间: {target_time}")

        # Windows系统设置
        class SYSTEMTIME(ctypes.Structure):
            _fields_ = [
                ("wYear", ctypes.c_uint16),
                ("wMonth", ctypes.c_uint16),
                ("wDayOfWeek", ctypes.c_uint16),
                ("wDay", ctypes.c_uint16),
                ("wHour", ctypes.c_uint16),
                ("wMinute", ctypes.c_uint16),
                ("wSecond", ctypes.c_uint16),
                ("wMilliseconds", ctypes.c_uint16)
            ]

        system_time = SYSTEMTIME()
        system_time.wYear = target_time.year
        system_time.wMonth = target_time.month
        system_time.wDay = target_time.day
        system_time.wHour = target_time.hour
        system_time.wMinute = target_time.minute
        system_time.wSecond = target_time.second

        # 加载系统库
        kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

        # 尝试设置系统时间
        if not kernel32.SetLocalTime(ctypes.byref(system_time)):
            error_code = ctypes.get_last_error()
            if error_code == 5:  # ERROR_ACCESS_DENIED
                 result.info = "需要管理员权限！请以管理员身份运行程序"
            else:
                result.info = "系统时间设置失败 (错误代码: {error_code})"
            return result
        result.state = True
        return result
    except ValueError:
        result.info = "时间格式错误！请使用 'YYYY-MM-DD HH:MM:SS' 格式"
    except Exception as e:
        result.info  =f"发生未知错误: {str(e)}"
    return result

if __name__ == "__main__":
    try:
        set_system_time("2025-10-10 10:51:33")
    except Exception as e:
        print(f"错误: {str(e)}")
        print("\n解决方案:")
        print("1. Windows: 右键点击Python脚本 -> '以管理员身份运行'")
        print("2. Linux: 在命令前加上sudo -> 'sudo python3 set_system_time.py \"2025-10-10 10:51:33\"'")
        sys.exit(1)